package com.wwwc.index.web.servlet;

import java.io.*;
import java.awt.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.ServletRequestWrapper;
import java.net.*;

import com.wwwc.util.web.*;
import com.wwwc.index.web.ejb.database.*;

public class StockHotListServlet extends HttpServlet {
    private EJBDatabaseQuery ejbdb;
    private DecimalFormat td = new DecimalFormat("0.00");

    public void doPost(HttpServletRequest request, HttpServletResponse response)
	throws IOException, ServletException
    {
        response.setContentType("text/html");
	HttpSession session  = request.getSession(true);
        PrintWriter out      = response.getWriter();
	String user_ip       = request.getRemoteAddr();

	String user_name   = null;
	String user_age    = null;
	String user_level  = null;
	String user_fname  = null;
	String user_since  = null;
	String user_edu    = null;
	String user_zip    = null;
	String user_sex    = null;

	ResourceBundle SystemInfo = (ResourceBundle)session.getAttribute("SystemInfo");
	
	if (SystemInfo == null) {
	    Locale locale = request.getLocale();
	    SystemInfo = ResourceBundle.getBundle("SystemInfo", locale.getDefault()); 
	    System.out.println((locale.getDefault()).getDisplayCountry());
	    session.setAttribute("SystemInfo", SystemInfo);
	}

	Hashtable user_info = (Hashtable)session.getAttribute("user_info");
	if(user_info==null) {
	    System.out.println("StockHotListServlet:Error:101");
	    return;
	}
	else {
	    user_name   = (String)user_info.get("user_name");
	    user_age    = (String)user_info.get("user_age");
	    user_level  = (String)user_info.get("user_level");
	    user_fname  = (String)user_info.get("user_fname");
	    user_since  = (String)user_info.get("user_since");
	    user_edu    = (String)user_info.get("user_edu");
	    user_zip    = (String)user_info.get("user_zip");
	    user_sex    = (String)user_info.get("user_sex");
	}

	String mid = (String)request.getAttribute("mid");
	
	//////////////////////////////////////////////////////////////////////////////
	// access control
	//////////////////////////////////////////////////////////////////////////////

	Hashtable achs = (Hashtable)request.getAttribute("achs");
	if(achs == null) {
	    System.out.println("StockHotListServlet:Error:103");
	    return;
	}

	int read_level     = Integer.parseInt((String)achs.get("read_level"));
	int read_age       = Integer.parseInt((String)achs.get("read_age"));
	int post_level     = Integer.parseInt((String)achs.get("post_level"));
	int post_age       = Integer.parseInt((String)achs.get("post_age"));

	boolean manager  = (Boolean.valueOf((String)achs.get("show_manager"))).booleanValue();
	boolean admin    = (Boolean.valueOf((String)achs.get("show_admin"))).booleanValue();

	String call_path =  request.getContextPath()+request.getServletPath();

	if(ejbdb == null) {
	    ejbdb= (new DatabaseEJBQuery()).getEJBDatabaseQuery();
	}

	String query = null;
	String action = request.getParameter("aid");

	//////////////////////////////////////////////////////////////////////////////
	// Hot List
	//////////////////////////////////////////////////////////////////////////////

	if(action == null || action.equals("0")) {
	    int row_counter = ejbdb.getRowCounter("STOCK_HOT_LIST_TITLE");
	    if(row_counter == -1) {
		out.println("<h3>Sorry. Please try again!</h3>");
		return;
	    }

	    String page = request.getParameter("pid");
	    if(page == null) {
		page = "1";
	    }
	    
	    out.println(MyHtml.pageCounter(row_counter, 2, Integer.parseInt(page), call_path+"?mid="+mid));
	    out.println((new ServletBean()).getSubdirInfo(request));

	    if(manager || admin) {
		out.println("<TABLE><TR>");
		out.println("<TD>"+MyHtml.makeLinkButton("Add", call_path+"?mid="+mid+"&aid=3-0")+"</TD>");
		out.println("<TD>"+MyHtml.makeLinkButton("Delete", call_path+"?mid="+mid+"&aid=4-0&pid="+page)+"</TD>");
		out.println("</TR></TABLE>");
	    }

	    StringBuffer sbf = new StringBuffer();

	    String dd = null;
	    String ud = null;
	    String p1 = null;
	    String p2 = null;
	    String v1 = null;
	    String v2 = null;

	    String[] up_down = {"Top Up<img src=/images/up.gif border=0>","Top Down<img src=/images/down.gif border=0>"};
	    
	    StringBuffer sbf3 = new StringBuffer();
	    query = "SELECT LIMIT "+(Integer.parseInt(page)-1)*2+" 2 * FROM STOCK_HOT_LIST_TITLE ORDER BY ID DESC, UP_DOWN;";
	    ArrayList alist = ejbdb.select(query);
	    if(alist == null || alist.isEmpty()) {
		return;
	    }

	    ArrayList a = null;
	    Iterator it = alist.iterator();
	    while (it.hasNext()) {
		a = (ArrayList)it.next();
		dd = (String)a.get(0);
		ud = (String)a.get(1);
		p1 = (String)a.get(2);
		p2 = (String)a.get(3);
		v1 = (String)a.get(4);
		v2 = (String)a.get(5);

		sbf3.append("<TABLE width=100% border=0>");

		if(ud.equals("1")) {
		    sbf3.append("\n<TR><TD align=center>");
		}
		else {
		    sbf3.append("\n<TR><TD align=center>");
		}

		sbf3.append((new Date(Long.parseLong(dd)))+" "+up_down[Integer.parseInt(ud)]+" List.<BR>");

		sbf3.append("\n<B>Price range form [$"+p1+"] To [$"+p2+"]. Volume range from ["+v1+"] TO ["+v2+"]</B>");
		sbf3.append("\n</TD></TR>");
		sbf3.append("\n</TABLE>");
		
		query = "SELECT * FROM STOCK_HOT_LIST_DATA WHERE FIELD1='"+dd+"';";
	        ArrayList ad = ejbdb.select(query);

		sbf3.append("\n<TABLE width=100%>");
		sbf3.append("\n<TR>");
		sbf3.append("\n<TD align='center' style='BORDER: 1px solid #669999;'><B>Chart</B></TD>");
		sbf3.append("\n<TD align='center' style='BORDER: 1px solid #669999;'><B>Price</B></TD>");
		sbf3.append("<TD align='center' style='BORDER: 1px solid #669999;'><B>Change</B></TD>");
		sbf3.append("\n<TD align='center' style='BORDER: 1px solid #669999;'><B>Chagne%</B></TD>");
		sbf3.append("<TD align='center' style='BORDER: 1px solid #669999;'><B>Volume</B></TD>");
		sbf3.append("\n<TD align='center' style='BORDER: 1px solid #669999;'><B>52W High</B></TD>");
		sbf3.append("<TD align='center' style='BORDER: 1px solid #669999;'><B>52W Low</B></TD>");
		sbf3.append("\n<TD align='center' style='BORDER: 1px solid #669999;'><B>P/E</B></TD>");
		sbf3.append("<TD align='center' style='BORDER: 1px solid #669999;'><B>Market Cap</B></TD>");
		sbf3.append("</TR>");

		Iterator itd = ad.iterator();
		String H52 = null;
		String L52 = null;

		while (itd.hasNext()) {
		    ArrayList ard = (ArrayList)itd.next();  

		    sbf3.append("\n<TR>");

		    sbf3.append("<TD align='left' style='BORDER: 1px solid #669999;'>&nbsp;&nbsp;&nbsp;");
		    sbf3.append("\n<A href='"+call_path+"?mid="+mid+"&aid=1&tick="+ard.get(1)+"&pid="+page+"' ");
		    sbf3.append(" title='"+ard.get(2)+"'>");
		    sbf3.append(ard.get(1)+"</A></TD>");
		    sbf3.append("\n<TD align='right' style='BORDER: 1px solid #669999;'>"+ard.get(3)+"</TD>");
		    sbf3.append("\n<TD align='right' style='BORDER: 1px solid #669999;'>"+ard.get(4)+"</TD>");
		    sbf3.append("\n<TD align='right' style='BORDER: 1px solid #669999;'>"+ard.get(5)+"</TD>");
		    sbf3.append("\n<TD align='right' style='BORDER: 1px solid #669999;'>"+ard.get(6)+"</TD>");
		    H52 = (String)ard.get(8);
		    L52 = (String)ard.get(9);
		    if(MyUserInputCheck.checkMoney(H52)) {
			H52 = td.format(Double.parseDouble(H52));
		    }
		    sbf3.append("\n<TD align='right' style='BORDER: 1px solid #669999;'>"+H52+"</TD>");
			
		    if(MyUserInputCheck.checkMoney(L52)) {
			L52 = td.format(Double.parseDouble(L52));
		    }
		    sbf3.append("\n<TD align='right' style='BORDER: 1px solid #669999;'>"+L52+"</TD>");

		    sbf3.append("\n<TD align='right' style='BORDER: 1px solid #669999;'>"+ard.get(10)+"</TD>");
		    sbf3.append("\n<TD align='right' style='BORDER: 1px solid #669999;'>"+ard.get(11)+"</TD>");
		    sbf3.append("</TR>");
		}
		sbf3.append("\n</TABLE>");
	    }
	    
	    sbf.append(sbf3);
	    out.println(sbf);
	    return;
	}

	if(action.equals("1")) {
	    String back_page_id = request.getParameter("pid");
	    String tick = request.getParameter("tick");
	    String tick_sid = ejbdb.selectSingleFieldValue("SELECT  DISTINCT SID FROM STOCK_SID WHERE TICK='"+tick+"';","SID");
	    String sector = "n/a";
	    String volume_link = call_path+"?mid="+mid+"&aid=2&tick="+tick;

	    GenerateStockChart gc = new GenerateStockChart();
	    out.println(gc.getChart(tick, tick_sid, sector, volume_link));
	    return;
	}

	if(action.equals("2")) {
	    String tick = request.getParameter("tick");
	    out.println((new StockVolumeBean()).getVolume(tick));
	    return;
	}

	//======================================================================================
	// Generate hot list
	//======================================================================================
	if(action.equals("3-0")) {
	    StockHotList shl = new StockHotList();
	    StringBuffer sb  = new StringBuffer();
	    sb.append("\n<input type=hidden name=aid value=3-1>");
	    sb.append("\n<input type=hidden name=mid value="+mid+">");
	    sb = shl.getRangeForm(call_path,sb);
	    out.println(MyHtml.getPageHead("Title:Stock Hot List Generator", "", "center", sb));
	    return;
	}

	if(action.equals("3-1")) {
	    String data_url_up = SystemInfo.getString("datek.url.screen.up");
	    String data_url_dn = SystemInfo.getString("datek.url.screen.dn");
	    String price1 = request.getParameter("up1");
	    String price2 = request.getParameter("up2");
	    String volum1 = request.getParameter("uv1");
	    String volum2 = request.getParameter("uv2");

	    long t1 = System.currentTimeMillis();

	    String huq="INSERT INTO STOCK_HOT_LIST_TITLE VALUES("+t1+",0,'"+price1+"','"+price2+"','"+volum1+"','"+volum2+"');";

	    String fup[] = {"0", request.getParameter("urst"), price1, price2,"0","0.01", volum1, volum2, "0"};

	    price1 = request.getParameter("dp1");
	    price2 = request.getParameter("dp2");
	    volum1 = request.getParameter("dv1");
	    volum2 = request.getParameter("dv2");

	    String hdq="INSERT INTO STOCK_HOT_LIST_TITLE VALUES("+(t1+1)+",1,'"+price1+"','"+price2+"','"+volum1+"','"+volum2+"');";
	    String fdn[] = {"1", request.getParameter("drst"), price1, price2,"1","0.01", volum1, volum2, "0"};

	    String temp = null;

	    for(int n=0; n < fup.length; n++){
		temp = fup[n];
		if(temp.indexOf(",") != -1) {
		    temp = temp.replaceAll(",","");
		}

		data_url_up = data_url_up.substring(0, data_url_up.indexOf("<+FIELD"+n+"+>"))+temp+
		    data_url_up.substring(data_url_up.indexOf("<+FIELD"+n+"+>")+10);
		
		temp = fdn[n];
		if(temp.indexOf(",") != -1) {
		    temp = temp.replaceAll(",","");
		}
		data_url_dn = data_url_dn.substring(0, data_url_dn.indexOf("<+FIELD"+n+"+>"))+temp+
		    data_url_dn.substring(data_url_dn.indexOf("<+FIELD"+n+"+>")+10);
	    }
	    
	    out.println("\n<CENTER>");
	    out.println("\n<TABLE border=1  cellSpacing=0 cellPadding=0 style='font-size: 10pt' width=100%>");
	    if(manager || admin){
		out.println("\n<TR><TD colspan=11 align=center><A href="+data_url_up+">Top UP [Local Only]</A></TD></TR>");
	    }

	    out.println("\n<TR><TD colspan=11 align=center>Top UP List</TD></TR>");
	    MyHttpsConnection cn = new MyHttpsConnection();
	    cn.connectToUrl(data_url_up);
	    String filter[]={"+","to<"};

	    Vector v = cn.getReturnRangeTextLineVector("Symbol","Previous", filter);
	    Enumeration enum = v.elements();

	    String field = null;

	    String query_head = "INSERT INTO STOCK_HOT_LIST_DATA VALUES(";
	    StringBuffer qbf = new StringBuffer();
	    StringBuffer fbf = null;
	    
	    String[] f = {"","","","","","","","","","",""};
	    int t =0;

	    while (enum.hasMoreElements()) {
		field  = (String)enum.nextElement();
		if(field.indexOf("'") != -1) {
		    field = field.replaceAll("'","''");
		}

		f[t] = field;
		t++;
		if(t<11) {
		    continue;
		}

		fbf = new StringBuffer("");

		out.println("\n<TR>");
		for(int m=0; m<f.length; m++) {
		    if(f[0].equals("Symbol")) {
			out.println("\n<TD>"+f[m]+"</TD>");
		    }
		    else {
			if(m==0) {
			    out.print("<TD><A href="+call_path);
			    out.println("?mid="+mid+"&aid=2&tick="+f[0]+">");
			    out.println(f[0]+"</A></TD>");
			    fbf.append("'"+f[0]+"',");
			}
			else {
			    out.println("\n<TD>"+f[m]+"</TD>");
			    if(m==f.length-1) {
				fbf.append("'"+f[m]+"');");
			    }
			    else {
				fbf.append("'"+f[m]+"',");
			    }
			}
		    }
		}
		out.println("\n</TR>");
		if(fbf.toString().length()>1) {
		    qbf.append(query_head+"'"+t1+"',"+fbf);
		}
		t=0;
	    }

	    out.println("\n</TABLE>");
	    out.println("\n<BR><BR>");

	    out.println("\n<TABLE border=1  cellSpacing=0 cellPadding=0 style='font-size: 10pt' width=100%>");
	    if(manager || admin){
		out.println("\n<TR><TD colspan=11 align=center><A href="+data_url_dn+">Top Down [Local Only]</A></TD></TR>");
	    }
	    out.println("\n<TR><TD colspan=11 align=center>Top Down List</TD></TR>");
	    cn.connectToUrl(data_url_dn);
	    v = cn.getReturnRangeTextLineVector("Symbol","Previous", filter);
	    enum = v.elements();
	    t =0;
	    while (enum.hasMoreElements()) {
		field  = (String)enum.nextElement();
		if(field.indexOf("'") != -1) {
		    field = field.replaceAll("'","''");
		}

		f[t] = field;
		t++;
		if(t<11) {
		    continue;
		}

		fbf = new StringBuffer("");

		out.println("\n<TR>");
		for(int m=0; m<f.length; m++) {
		    if(f[0].equals("Symbol")) {
			out.println("\n<TD>"+f[m]+"</TD>");
		    }
		    else {
			if(m==0) {
			    out.print("<TD><A href="+call_path);
			    out.println("?mid="+mid+"&aid=1&tick="+f[0]+">");
			    out.println(f[0]+"</A></TD>");
			    fbf.append("'"+f[0]+"',");
			}
			else {
			    out.println("\n<TD>"+f[m]+"</TD>");
			    if(m==f.length-1) {
				fbf.append("'"+f[m]+"');");
			    }
			    else {
				fbf.append("'"+f[m]+"',");
			    }
			}
		    }
		}
		out.println("\n</TR>");
		if(fbf.toString().length()>1) {
		    qbf.append(query_head+"'"+(t1+1)+"',"+fbf);
		}
		t=0;
	    }

	    out.println("\n</TABLE>");
	    out.println("\n<BR><BR>");
	    out.println("\n<FORM method=post action="+call_path+">");
	    out.println("\n<TABLE border=1  cellSpacing=0 cellPadding=0 style='font-size: 10pt' width=100%>");
	    out.println("\n<TR><TD><TEXTAREA name=huq rows=2 cols=120>"+huq+"</TEXTAREA></TD></TR>");
	    out.println("\n<TR><TD><TEXTAREA name=hdq rows=2 cols=120>"+hdq+"</TEXTAREA></TD></TR>");
	    out.println("\n<TR><TD><TEXTAREA name=query rows=10 cols=120>"+qbf+"</TEXTAREA></TD></TR>");
	    out.println("\n<TR><TD align=center><input type=submit name=B value=Save style='font-size: 8pt'></TD></TR>");
	    out.println("\n</TABLE>");
	    out.println("\n<input type=hidden name=mid value="+mid+">");
	    out.println("\n<input type=hidden name=aid value=3-2>");
	    out.println("\n</FORM>");
	    out.println("\n</BODY></HTML>");
	    return;
	}

	
	if(action.equals("3-2")) { //save data
	    String huq = request.getParameter("huq");
	    String hdq = request.getParameter("hdq");
	    String dataq = request.getParameter("query");

	    if(huq == null || hdq == null || dataq == null || huq.length()<1 || hdq.length()<1 || dataq.length() <1) {
		return;
	    } 

	    StringBuffer qbf = new StringBuffer();
	    qbf.append(huq);
	    qbf.append(hdq);
	    qbf.append(dataq);

	    if(ejbdb.insert(qbf.toString()) <0) {
		if(manager) {
		    out.println(MyMessage.htmlMessage("Save data error!"));
		}

		if(admin) {
		    out.println("<TABLE><TR><TD align=left style='font-size:8pt'>");
		    String temp = qbf.toString();
		    out.println(temp.replaceAll(";",";</TD></TR></TABLE><TABLE><TR><TD align=left  style='font-size:8pt'>"));
		    out.println("</TD></TR></TABLE>");
		}
		return;
	    }
	    else {
		out.println(MyMessage.htmlMessage("Saved"));
	    }
	    return;
	}

	if(action.equals("4-0")) {
	    String page = request.getParameter("pid");
	    if(page == null) {
		return;
	    }

	    query = "SELECT LIMIT "+(Integer.parseInt(page)-1)*2+" 2 * FROM STOCK_HOT_LIST_TITLE ORDER BY ID DESC, UP_DOWN;";
	    Vector v = ejbdb.selectSingleFieldValueVector(query, "ID");
	    Enumeration enum = v.elements();
	    String id = null;
	    StringBuffer qsbf = new StringBuffer();
	    while(enum.hasMoreElements()) {
		id = (String)enum.nextElement();
		qsbf.append("DELETE FROM STOCK_HOT_LIST_TITLE WHERE ID="+id+";");
		qsbf.append("DELETE FROM STOCK_HOT_LIST_DATA WHERE FIELD1='"+id+"';");
	    }
	    
	    if(ejbdb.delete(qsbf.toString())<0) {
		out.println("Error:<BR>"+qsbf);
	    }
	    else {
		out.println("Deleted");
	    }
	}
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
	throws IOException, ServletException
    {
	doPost(request, response);
    }
}






